<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">登录历史</h2>
    </div>

    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="用户名">
          <el-input
            v-model="filterForm.username"
            placeholder="请输入用户名"
            clearable
            @clear="handleFilter"
          />
        </el-form-item>
        
        <el-form-item label="IP地址">
          <el-input
            v-model="filterForm.ip"
            placeholder="请输入IP地址"
            clearable
            @clear="handleFilter"
          />
        </el-form-item>
        
        <el-form-item label="登录状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="请选择" 
            clearable 
            @change="handleFilter"
            style="width: 140px"
          >
            <el-option label="成功" value="success" />
            <el-option label="失败" value="fail" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleFilter"
            style="width: 380px"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-card class="content-card">
      <el-table
        v-loading="loading"
        :data="loginList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="location" label="登录地点" />
        <el-table-column prop="device" label="设备信息" />
        <el-table-column prop="browser" label="浏览器" />
        <el-table-column prop="os" label="操作系统" />
        <el-table-column prop="login_time" label="登录时间" width="170" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <h2 class="page-title">登录统计</h2>
      <div class="stats-cards">
        <el-card class="stats-card today-card">
          <div class="stats-title">今日登录次数</div>
          <div class="stats-value">{{ stats.todayLogins }}</div>
        </el-card>
        
        <el-card class="stats-card week-card">
          <div class="stats-title">本周登录次数</div>
          <div class="stats-value">{{ stats.weekLogins }}</div>
        </el-card>
        
        <el-card class="stats-card month-card">
          <div class="stats-title">本月登录次数</div>
          <div class="stats-value">{{ stats.monthLogins }}</div>
        </el-card>
        
        <el-card class="stats-card failed-card">
          <div class="stats-title">登录失败次数</div>
          <div class="stats-value">{{ stats.failedLogins }}</div>
        </el-card>
      </div>
      
      <!-- 登录趋势图 -->
      <el-card class="trend-card">
        <template #header>
          <div class="card-header">
            <span>登录趋势</span>
            <el-radio-group v-model="trendType" size="small" @change="updateTrendChart">
              <el-radio-button value="week">最近一周</el-radio-button>
              <el-radio-button value="month">最近一月</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-container" ref="trendChartRef"></div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts/core'
import { getLoginHistoryList, getLoginStats, getLoginTrend } from '@/api/history'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

// 注册必需的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  BarChart,
  CanvasRenderer
])

// 登录列表数据
const loading = ref(false)
const loginList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选表单
const filterForm = reactive({
  username: '',
  ip: '',
  status: '',
  dateRange: []
})

// 统计数据
const stats = reactive({
  todayLogins: 0,
  weekLogins: 0,
  monthLogins: 0,
  failedLogins: 0
})

// 趋势图
const trendChartRef = ref(null)
const trendType = ref('week')
let trendChart = null

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchLoginList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchLoginList()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchLoginList()
}

// 重置筛选
const resetFilter = () => {
  filterForm.username = ''
  filterForm.ip = ''
  filterForm.status = ''
  filterForm.dateRange = []
  handleFilter()
}

// 获取登录历史列表
const fetchLoginList = async () => {
  loading.value = true
  try {
    const response = await getLoginHistoryList({
      page: currentPage.value,
      limit: pageSize.value,
      username: filterForm.username,
      ip_address: filterForm.ip,
      status: filterForm.status,
      start_date: filterForm.dateRange ? filterForm.dateRange[0] : undefined,
      end_date: filterForm.dateRange ? filterForm.dateRange[1] : undefined
    })
    
    if (response.code === 200) {
      loginList.value = response.data
      total.value = response.total
    }
    loading.value = false
  } catch (error) {
    console.error('获取登录历史列表失败:', error)
    ElMessage.error('获取登录历史列表失败')
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await getLoginStats()
    if (response.code === 200) {
      stats.todayLogins = response.data.todayLogins
      stats.weekLogins = response.data.weekLogins
      stats.monthLogins = response.data.monthLogins
      stats.failedLogins = response.data.failedLogins
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 初始化趋势图
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  try {
    trendChart = echarts.init(trendChartRef.value)
    updateTrendChart()
    
    window.addEventListener('resize', () => {
      trendChart && trendChart.resize()
    })
  } catch (error) {
    console.error('初始化趋势图失败:', error)
  }
}

// 更新趋势图数据
const updateTrendChart = async () => {
  if (!trendChart) return
  
  try {
    const response = await getLoginTrend(trendType.value)
    
    let xData = []
    let successData = []
    let failData = []
    
    if (response.code === 200) {
      xData = response.data.dates
      successData = response.data.success
      failData = response.data.fail
    }
    
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['登录成功', '登录失败']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: xData
      },
      yAxis: {
        type: 'value',
        minInterval: 1
      },
      series: [
        {
          name: '登录成功',
          type: 'bar',
          stack: 'total',
          data: successData,
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '登录失败',
          type: 'bar',
          stack: 'total',
          data: failData,
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    }
    
    trendChart.setOption(option)
  } catch (error) {
    console.error('更新趋势图失败:', error)
  }
}

onMounted(() => {
  fetchLoginList()
  fetchStats()
  
  // 使用nextTick确保DOM已经渲染
  setTimeout(() => {
    initTrendChart()
  }, 100)
})

onUnmounted(() => {
  if (trendChart) {
    trendChart.dispose()
    trendChart = null
  }
  
  // 移除resize事件监听
  window.removeEventListener('resize', () => {
    trendChart && trendChart.resize()
  })
})
</script>

<style lang="scss" scoped>
.departments-container {
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .filter-section {
    margin-bottom: 20px;
    
    .filter-form {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .stats-section {
    margin-top: 30px;
    
    .stats-cards {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;
      margin-bottom: 20px;
      
      .stats-card {
        position: relative;
        overflow: hidden;
        
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          opacity: 0.8;
          z-index: 0;
        }
        
        .stats-title, .stats-value {
          position: relative;
          z-index: 1;
          color: white;
          text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.2);
        }
        
        .stats-title {
          font-size: 14px;
          font-weight: 500;
          padding: 8px 16px;
          border-bottom: 1px solid rgba(255, 255, 255, 0.3);
          margin-bottom: 6px;
          text-align: center;
        }
        
        .stats-value {
          font-size: 28px;
          font-weight: bold;
          text-align: center;
          padding: 10px 0;
        }
        
        &.today-card::before {
          background: linear-gradient(135deg, #42b0ff 0%, #0074e1 100%);
        }
        
        &.week-card::before {
          background: linear-gradient(135deg, #36d1dc 0%, #5b8def 100%);
        }
        
        &.month-card::before {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.failed-card::before {
          background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
        }
      }
    }
    
    .trend-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      
      .chart-container {
        height: 350px;
      }
    }
  }
}
</style> 